<template>
  <div>
    <a-modal v-model="showModal"  title="请选择商品类目" @ok="handleOk" @cancel="handleCancel">
      <a-tree
        v-model="checkedKeys"
        checkable
        :expanded-keys="expandedKeys"
        :auto-expand-parent="autoExpandParent"
        :selected-keys="selectedKeys"
        :tree-data="treeData"
        @expand="onExpand"
        @select="onSelect"
        @check="onCheck"
      />
    </a-modal>
  </div>
</template>
<script>
import { getAction } from '@/api/manage'
export default {
  props:{
    currentChecked:{
      type:Array,
      default:null
    },
    categoryIds:{
      type:String,
      default:''
    }
  },
  data() {
    return {
      treeData:[],
      showModal:false,
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      dataList:[]
    }
  },
  watch:{
    currentChecked(newValue, oldValue){
      // console.log(newValue, oldValue)
    },
    categoryIds(newValue, oldValue){
      // console.log(newValue, oldValue)
      this.initDepartComponent()
      // if (newValue) {
      //   this.checkedKeys = newValue.split(',')
      // } else {
      //   this.checkedKeys = [];
      // }
    },
    showModal: {
      handler(newValue) {
        if(newValue){
          // console.log(this.categoryIds)
          if (this.categoryIds) {
            this.checkedKeys = this.categoryIds.split(",");
          } else {
            this.checkedKeys = [];
          }
        }
        
      }
    }
  },
  created() {
    this.fetchCategoryList()
  },
  mounted() {
    this.checkedKeys = this.currentChecked
  },
  methods: {
    // 商品类目
    fetchCategoryList(){
      let params = {
        code:'B06'
      }
      getAction('/sys/category/querySysCateTree',params).then(res =>{
        if(res.code==0){
          let arr = [...res.result]
          this.reWriterWithSlot(arr)
          this.treeData = res.result
          this.initDepartComponent()
        }else{
          this.$message.warning(res.msg)
        }
      })
    },
   show(){
     this.showModal = true
   },
   onExpand(expandedKeys) {
      // console.log('onExpand', expandedKeys);
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    onCheck(checkedKeys) {
      // console.log('onCheck', checkedKeys);
      this.checkedKeys = checkedKeys;
    },
    onSelect(selectedKeys, info) {
      this.selectedKeys = selectedKeys;
    },
    handleOk(){
      let rows = this.getCheckedRows(this.checkedKeys)
      console.log(rows)
      this.$emit('updateCategory',rows)
      this.showModal = false
    },
    handleCancel(){
      this.showModal = false
      this.checkedKeys = []
    },
    // 根据 checkedKeys 获取 rows
    getCheckedRows(checkedKeys) {
      const forChildren = (list, key) => {
        for (let item of list) {
          if (item.key === key) {
            return item
          }
          if (item.children instanceof Array) {
            let value = forChildren(item.children, key)
            if (value != null) {
              return value
            }
          }
        }
        return null
      }

      let rows = []
      for (let key of checkedKeys) {
        let row = forChildren(this.treeData, key)
        if (row != null) {
          rows.push(row)
        }
      }
      return rows
    },
    initDepartComponent(){
      let names = ''
      if(this.categoryIds){
        let currDepartId = this.categoryIds.split(',')
        for(let item of this.dataList){
          if(currDepartId.indexOf(item.key)>=0){
            names+=","+item.title
          }
        }
        if(names){
          names = names.substring(1)
        }
      }
      this.$emit("initComp",names)
    },
    reWriterWithSlot(arr){
      for(let item of arr){
        if(item.children && item.children.length>0){
          this.reWriterWithSlot(item.children)
          let temp = Object.assign({},item)
          temp.children = {}
          this.dataList.push(temp)
        }else{
          this.dataList.push(item)
          item.scopedSlots={ title: 'title' }
        }
      }
      // console.log(this.dataList)
    }
  },
}
</script>